/*
 * @Description: 断言方法：泛型 、 as、 typeof、 instanceof 、is 、 in
 * @Author: dh
 * @Date: 2021-09-24 15:16:29
 * @LastEditors: dh
 * @LastEditTime: 2023-01-09 10:52:33
 */

interface PeopleType {
	name: string
}
interface AnimalType {
	sex: string
}
type TwoType = PeopleType | AnimalType

function func4(value: any, obj: TwoType): any {
	// 泛型 断言
	;(<string>value).length

	// as 断言
	;(value as string).length

	// typeof 断言
	if (typeof value === 'number') {
		console.log(value.toFixed())
	} else {
		console.log(value.length)
	}

	// in 断言
	if ('name' in obj) {
		console.log(obj.name)
	} else if ('sex' in obj) {
		console.log(obj.sex)
	} else {
		const check = obj // never
	}

	// instanceof 断言
	if (value instanceof Date) {
		return value.getDate()
	}

	// is 这个不好用
	function isA(data: TwoType): data is PeopleType {
		return 'name' in data
	}

	function isB(data: TwoType): data is AnimalType {
		return 'sex' in data
	}

	if (isA(obj)) {
		console.log(obj.name)
	} else {
		console.log(obj.sex)
	}
}
